import 'package:flutter/foundation.dart'; // 用于判断是否是 Web 端
import 'package:flutter/material.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'dart:io';

class CustomNetworkImage extends StatefulWidget {
  final String imageUrl;
  final double width;
  final double height;
  final BoxFit fit;
  final String placeholderAsset;
  final String errorAsset;

  const CustomNetworkImage({
    Key? key,
    required this.imageUrl,
    this.width = 100,
    this.height = 100,
    this.fit = BoxFit.cover,
    this.placeholderAsset = 'assets/images/empty.png',
    this.errorAsset = 'assets/images/whatsapp.png',
  }) : super(key: key);

  @override
  _CustomNetworkImageState createState() => _CustomNetworkImageState();
}

class _CustomNetworkImageState extends State<CustomNetworkImage> {
  String? _cachedImagePath;
  bool _loading = true;

  @override
  void initState() {
    super.initState();
    _loadImage();
  }

  Future<void> _loadImage() async {
    try {
      final cacheManager = DefaultCacheManager();
      if (kIsWeb) {
        // Web 端直接使用网络图片，不缓存到本地
        _cachedImagePath = widget.imageUrl;
      } else {
        // Android/iOS 端：下载图片并缓存到本地
        final file = await cacheManager.getSingleFile(widget.imageUrl);
        _cachedImagePath = file.path;
      }
    } catch (e) {
      _cachedImagePath = null;
    } finally {
      if (mounted) {
        setState(() {
          _loading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_loading) {
      return Image.asset(widget.placeholderAsset,
          width: widget.width, height: widget.height, fit: widget.fit);
    }

    if (_cachedImagePath != null) {
      return kIsWeb
          ? Image.network(_cachedImagePath!,
              width: widget.width, height: widget.height, fit: widget.fit)
          : Image.file(File(_cachedImagePath!),
              width: widget.width, height: widget.height, fit: widget.fit);
    }

    return Image.asset(widget.errorAsset,
        width: widget.width, height: widget.height, fit: widget.fit);
  }
}
